package ${package}.utils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
* 全局日志
*
* @author ${author}
* @date ${date}
*/
@Aspect
@Component
@Slf4j
public class LogAspect {

    /**
     * 定义切入点，拦截所有接口
     */
    @Pointcut("execution(* ${package}.controller..*.*(..))")
    public void logPointcut() {

    }

    @Around("logPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        long start = System.currentTimeMillis();
        try {
            log.info("请求地址：{}", request.getRequestURI());
            log.info("请求参数：{}", JSONUtil.toJsonStr(joinPoint.getArgs()));
            Object result = joinPoint.proceed();
            long end = System.currentTimeMillis();
            log.info("本次请求执行时间：{}", (end - start) + "ms!");
            return result;
        } catch (Throwable e) {
            log.error("请求失败原因：", e);
            return Result.error(e.getMessage());
        }
    }

}
